package com.example.myapplication.ui.notifications;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

public class NotificationsViewModel extends ViewModel {
    private static final String TAG = "NotificationsViewModel";

    private MutableLiveData<String> mText;

    private MutableLiveData<LoginBean> loginBeanMutableLiveData = new MutableLiveData<LoginBean>();

    public MutableLiveData<LoginBean> getLoginBeanMutableLiveData() {
        return loginBeanMutableLiveData;
    }

    public NotificationsViewModel() {
        mText = new MutableLiveData<>();
        mText.setValue("This is notifications fragment");
    }

    public LiveData<String> getText() {
        return mText;
    }

    public void getData(final Context context, String name, String password) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("username",name);
            jsonObject.put("password",password);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String url ="http://124.93.196.45:10001/prod-api/api/login";
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        JsonObjectRequest request = new JsonObjectRequest(
                Request.Method.POST,
                url,
                jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.e(TAG, "onResponse: "+jsonObject.toString() );

                        Gson gson = new Gson();
                        LoginBean loginBean = gson.fromJson(jsonObject.toString(), LoginBean.class);
                        loginBeanMutableLiveData.postValue(loginBean);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                }

        ); // 五个参数
        requestQueue.add(request);
    }

}